package com.example.blog.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @Author: lu
 * @Date: 2023-10-10-19:48
 * @Description: token生成及验证
 */
public class JwtUtil {
    private  static String SECRET = "token@#12345";

    /**
     * 生成token
     */
    public static  String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();

        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        //获取系统当前时间，默认七天过期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,6);

        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
        String token = builder.sign(Algorithm.HMAC256(SECRET));//签名
        return  token;
    }

    /**
     * 验证token
     */
    public static DecodedJWT verify(String token){
        //如果有任何异常，此处都会抛出异常
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return  decodedJWT;
    }

}
